package com.geralt.im.jms;


import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;

import com.geralt.im.model.NeedReplyMessage;



public class MessageQueueProducer {
	private Connection conn;
	private ConnectionFactory cf;
	private Session session;
	private Destination queue;
	private MessageProducer producer;
	private String url;
	private String queue_name;
	public MessageQueueProducer(){}
	public MessageQueueProducer(String url,String queue_name){
		this.url = url;
		this.queue_name = queue_name;
		this.createConnet();
	}
	public void createConnet(){
		cf = new ActiveMQConnectionFactory(url);
		try {
			conn = cf.createConnection();
			session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
			queue = new ActiveMQQueue(queue_name);
			producer = session.createProducer(queue);
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void start(){
		try {
			conn.start();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void send(NeedReplyMessage msg){
		TextMessage tm;
		try {
			tm = session.createTextMessage();
			tm.setText(msg.getContent());
			tm.setJMSReplyTo(queue);
			tm.setJMSCorrelationID(msg.getUuid());
			producer.send(tm);
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	public void commit(){
		try {
			session.commit();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void close_all(){
		try {
			session.close();
			producer.close();
			conn.close();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
